using net_work.Config;
using net_work.Data.DTO.Hmw;
using net_work.Data.Entity.Hmw;
using net_work.IRepository.Hmw;

namespace net_work.Repository.Hmw;

public class HomeworkQuestionRepository(ApplicationDbContext dbContext)
    : Repository<HomeworkQuestion>(dbContext), IHomeworkQuestionRepository
{
    public async Task<int> InsertAsync(HomeworkQuestionAddRequest homeworkQuestionAddRequest)
    {
        foreach (var newHomeworkQuestion in homeworkQuestionAddRequest.BankQuestionIds.Select(bankQuestionId =>
                     new HomeworkQuestion
                     {
                         Remark = homeworkQuestionAddRequest.Remark,
                         BankQuestionId = bankQuestionId,
                         HomeworkId = homeworkQuestionAddRequest.HomeworkId
                     }))
        {
            await dbContext.HomeworkQuestions.AddAsync(newHomeworkQuestion);
        }

        return await dbContext.SaveChangesAsync();
    }

    public async Task<bool> UpdateAsync(HomeworkQuestionUpdateRequest homeworkQuestionUpdateRequest)
    {
        var homeworkQuestion = await dbContext.HomeworkQuestions.FindAsync(homeworkQuestionUpdateRequest.Id);
        if (homeworkQuestion == null)
        {
            return false;
        }

        homeworkQuestion.Remark = homeworkQuestionUpdateRequest.Remark;
        homeworkQuestion.BankQuestionId = homeworkQuestionUpdateRequest.BankQuestionId;
        homeworkQuestion.HomeworkId = homeworkQuestionUpdateRequest.HomeworkId;

        await dbContext.SaveChangesAsync();
        return true;
    }
}